#!/bin/bash

# === 通用函数：只杀当前用户启动的进程 ===
function kill_if_running() {
    PROCESS_NAME=$1
    PID=$(ps -u $USER -o pid,cmd | grep "$PROCESS_NAME" | grep -v grep | awk '{print $1}')
    
    if [ ! -z "$PID" ]; then
        echo "⚠️ 检测到已有 $PROCESS_NAME 正在运行，PID=$PID，正在尝试关闭..."
        kill $PID
        sleep 2
        # 再次确认是否已关闭
        PID=$(ps -u $USER -o pid,cmd | grep "$PROCESS_NAME" | grep -v grep | awk '{print $1}')
        if [ ! -z "$PID" ]; then
            echo "⛔ 进程未正常退出，执行 kill -9 $PID"
            kill -9 $PID
        fi
        echo "✅ 已关闭旧的 $PROCESS_NAME 进程"
    else
        echo "✅ 没有正在运行的 $PROCESS_NAME"
    fi
}

# === 启动 Chatbot ===
echo "🟢 正在启动 Chatbot 后端服务..."
source /data/tmp_user/wangyifei/anaconda3/etc/profile.d/conda.sh
conda activate Chatbot

# 检查并杀掉已运行的 api_server.py
kill_if_running "api_server.py"

# 启动服务
nohup python api_server.py > chatbot.log 2>&1 &
CHATBOT_PID=$!
echo $CHATBOT_PID > chatbot.pid
echo "✅ Chatbot 已通过 nohup 启动，PID=$CHATBOT_PID，日志输出至 chatbot.log"

conda deactivate

# === 启动 Mineru ===
echo "🟢 正在启动 Mineru 后端服务..."
source /data/tmp_user/wangyifei/anaconda3/etc/profile.d/conda.sh
conda activate mineru

cd MinerU

# 检查并杀掉已运行的 pdfTools.py
kill_if_running "pdfTools.py"

# 启动服务
nohup python pdfTools.py > mineru.log 2>&1 &
MINERU_PID=$!
echo $MINERU_PID > ../mineru.pid

cd ..

echo "✅ Mineru 已通过 nohup 启动，PID=$MINERU_PID，日志输出至 mineru.log"
